import { routerRedux } from 'dva/router';
import { query as queryUsers, queryCurrent,getUserInfo } from '../services/user';


export default {
  namespace: 'user',

  state: {
    list: [],
    currentUser: {},
    menu:[],
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *getUserInfo(_, { call, put }) {// 获取用户信息
      const response = yield call(getUserInfo);
      if(response && response.success === 1) {
        yield put({
          type: 'saveCurrentUser',
          payload: { avatar: response.data.userInfo.avatarUrl,name:response.data.userInfo.nickName,userid:response.data.userInfo.userId },
        });
        yield put({
          type: 'saveMenuData',
          payload: response.data.menu,
        });
      }else{
        yield put(routerRedux.push({pathname: '/user/login'}));
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    saveMenuData(state, action) {
      return {
        ...state,
        menu: action.payload || [],
      };
    },
    changeNotifyCount(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload,
        },
      };
    },
  },
};
